const constant = require('../../../utils/constant.js');
var mRequest = require('./goodsDetailsService.js');
const utilService = require('../../../utils/utilService.js');
/** 页面显示类型 */
let intentType;
/** 下面list的位置高度 */
let listPosition;
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    addressData: null,           // 地址信息
    animationData: {},
    friendId: '',             // 邀请帮忙砍果冻朋友id
    tabRghtText: '',   // 底部tab默认文案
    scrollTop: 0,             // 回到顶部坐标
    goodsId: '1',             // 商品ID
    inputValue: '',           // 确认出果冻input值
    isFans: true,             // 是否关注过
    storyVideourl: '',        // 故事详情数据
    isStartVisible: true,     // 故事详情播放按钮是否显示
    isFollowVisible: false,   // 关注两个字是否显示
    isFollowRootVisible: false,// 关注view是否显示
    isTabRightVisible: false, // tab底部右边是够显示
    titleDetailsStatus: '',   // 顶部商品状态显示
    isStatusVisible: true,    // 顶部状态是否显示

    userName: '',             // 发布人名称
    userUrl: '',              // 发布人头像
    storyDetailsData: {},     // 故事详情data
    goodsDetailsData: {},     // 商品详情data   
    swiperData: {},           // 轮播图数据
    redObtainData: [],        // 领取成功的人数据 
    obtainNum: 0,             // 领取成功共多少人
    rewardData: {},           // 打赏人的数据

    rewardIntegral: 1,        // 商品默认打赏数量
    isPraiseVisible: false,   // 赞赏一颗果冻是否显示

    isInvitationVisible: false,// 邀请好友砍花 和砍花记录
    isObtainVisible: false,    // 领取成功
    isBiddersListVisible: true,// 竞拍记录
    isPeopleVisible: false,    // 认识的人是否显示
    isBottomRight: false,      // 底部右侧按钮是否变灰  true 灰色  false 红色

    robRuleData: {},           // 抢兑规则

    biddresData: {},           // 竞拍记录的数据
    biddresInfo: {},           // 竞拍信息数据
    biddersPage: 0,            // 竞拍记录的当前页数
    isSeeBiddersMore: true,    // 竞拍记录查看更多是否显示
    isBiddersVisible: true,    // 是不是竞拍中 true不是  false是

    userFollowerData: {},      // 可能认识的人数据
    defaultAddressData: null,    // 默认地址数据

    isSpeedVisible: true,      // 快速出花弹窗是否显示
    speedFolwerMsg: '是否快速出果冻',

    freightData: '',           // 获取运费Data

    isClickNumVisible: false,  // 赞赏按钮是否显示

    isTabLeftVisible: false,   // 底部tab左边是否 --抢兑

    indicatorDots: false,      // 是否显示面板指示点
    autoplay: false,           // 是否自动切换
    swiperLength: 0,           // 轮播图总的数量
    swiperCurrent: 1,          // 轮播图当前的数量

    cantangShareMsg: "",       // 砍糖分享信息
    shareMsg: "",               // 普通分享信息
    myOptions: null,
    isShareImgVisible: false,   // 是否显示商品审核中图片 false不是 true 是
    saleTypeId: 1,
    //"出售方式:1：默认出售方式，普通转售;2：团购;3：竞拍;4:一花购5：抢兑一口价 6：抢兑竞拍"
    isBuyShareMsg:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      myOptions: options
    })
    var self = this;
    self.getShareMessage(6)
    self.getShareMessage(7)
    self.getShareMessage(20)
  },

  onPullDownRefresh: function () {
    setTimeout(function () {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  //点击授权按钮回调
  authSuccess() {
    console.log("授权 信息", app.globalData.userInfo);
    this.initView();
    // 处理页面跳转过来的数据
    this.handleIntentData(this.data.myOptions);
    this.initRequestData();
  },

  onShow: function () {
    var self = this;
    //授权
    self.authAlert = self.selectComponent("#authAlert");
    self.authAlert.bindCatch()
    app.loginPromise.then(() => {
      self.initView()
      // 处理页面跳转过来的数据
      self.handleIntentData(self.data.myOptions);
      self.initRequestData();
      // 获取默认地址
      self.showDefaultAddress()
    });
  },

  /**
   * 赞赏成功后刷新果冻
   */
  refreshGoods: function () {
    var that = this
    var param = {
      id: this.data.goodsId
    }
    mRequest.getGoodsDetails(param,
      function (data) {
        that.setData({
          goodsDetailsData: data,
          swiperData: data.files.filePaths,
          rewardIntegral: data.rewardIntegral,
          userName: data.userName,
          userUrl: data.userAvatar
        })
        // 更新赞赏的数据
        that.praiseView.initData(data, that.data.goodsId)
        // 物品介绍和价钱View
        that.goodsInfoView.initGoodsData(data, intentType)
        // 刷新自己的果冻
        app.globalData.userSweets = data.userIntegral
      })
  },

  initView: function () {
    // 回到顶部view
    this.actionView = this.selectComponent("#actionView")
    // 获取要了popuwindow实例
    this.payPopuWindow = this.selectComponent("#payPopuWindow");
    // 获取立即竞拍pop实例
    this.biddersPopuWindow = this.selectComponent("#biddersPopuWindow");
    // 获取video实例
    this.showVideo = this.selectComponent("#showVideo");
    // 关注的人View
    this.followView = this.selectComponent("#followView")
    // 评论View
    this.comment = this.selectComponent("#comment")
    this.comment.requestComment(this.data.myOptions["goods_id"])
    // 可能认识的人
    this.possibleFriends = this.selectComponent("#possibleFriends");
    this.possibleFriends.ready()
    // 赞赏view
    this.praiseView = this.selectComponent("#praiseView")
    // 邀请好友砍价view
    this.cutJellyView = this.selectComponent("#cutJellyView")
    // 物品介绍、价钱等view
    this.goodsInfoView = this.selectComponent("#goodsInfoView")
    this.goodsInfoView.initData()
    // 计算View坐标
    this.queryMultipleNodes()
    // 获取相关更多的商品
    this.moreList = this.selectComponent("#more-list");
    // 0元抢兑popwindow
    this.robbingPopWindow = this.selectComponent("#robbingPopWindow")
  },

  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        console.log("分享数据", data)
        if (type == 7) {
          self.setData({
            cantangShareMsg: data.title
          })

        } else if (type == 6){
          self.setData({
            shareMsg: data.title
          })
        } else if (type == 20) {
          self.setData({
            isBuyShareMsg: data.title
          })
        }
      },
      function (error) {

      }
    );
  },

  initRequestData: function () {
    if (intentType == constant.DEFAULT || intentType == constant.BIDDERS) {   // 默认详情页
      // 根据商品ID获取该商品详情
      this.showGoodsDetails()
      // 获取已领取该商品的人
      this.showObtainSuccessPeople()
      // 获取砍花记录
      this.cutJellyView.initData()
    } else if (intentType == constant.STORY) {// 故事详情页
      // 请求故事详情页
      this.showStoryDetails()
    } else if (intentType == constant.ONE_MONEY) {
      // 根据商品ID获取该商品详情
      this.showGoodsDetails()
      // 获取规则
      this.showRobRule()
    }else{
      // 根据商品ID获取该商品详情
      this.showGoodsDetails()
    }
    // 可能认识的人
    this.showUserFollower();
  },

  showRobRule: function () {
    let that = this
    let params = {
      type: 10
    }
    mRequest.getRule(params,
      function (data) {
        that.setData({
          robRuleData: data
        })
      })
  },

  /**
   * 获取默认地址id
   */
  showDefaultAddress: function () {
    if (this.data.defaultAddressData != null){
      return;
    }
    var that = this
    var param = {
      userId: app.globalData.userId,
    }
    mRequest.getDefaultAddress(param,
      function (data) {
        that.setData({
          defaultAddressData: data
        })
      })
  },

  /**
   * 查询竞拍信息接口
   */
  showBiddersInfo: function () {
    var that = this
    var param = {
      goodsId: this.data.goodsId,
    }

    mRequest.queryBiddersInfo(param,
      function (data) {
        // 0、自己，1、其他人
        if (that.data.goodsDetailsData.userStatus == 1) {
          that.setData({
            isBottomRight: data.auctionStatus == 1 ? true : false, //右侧按钮显示竞拍结束 颜色变灰色 0进行中，1结束
            tabRghtText: data.auctionStatus == 1 ? '竞拍结束' : '立即竞拍'
          })
        }
        that.setData({
          biddresInfo: data,
        })
      })
  },

  /**
   * 获取竞拍记录接口
   */
  showBiddersData: function () {
    // 如果是自己发布商品，不需要请求
    if (this.data.goodsDetailsData.userStatus == 0) {
      return
    }
    var that = this
    var param = {
      goodsId: this.data.goodsId,
      startPage: this.data.biddersPage
    }

    mRequest.getBiddersData(param,
      function (data) {
        console.log('竞拍记录接口  成功')
        if (that.data.biddersPage == 0) {
          if (data.items.length > 0) {
            that.setData({
              biddresData: data,
              isSeeBiddersMore: false,      // 竞拍查看更多显示
              isBiddersListVisible: false   // 竞拍记录样式显示
            })
          } else {
            that.setData({
              isSeeBiddersMore: true,
              isBiddersListVisible: true
            })
          }

        } else {
          if (data.items.length > 0) {
            let allData = that.data.biddresData.items.concat(data.items)
            that.data.biddresData.items = allData
            that.setData({
              biddresData: that.data.biddresData
            })
          } else {
            that.showTost('没有更多数据');
            let page = that.data.biddersPage - 1
            that.setData({
              isSeeBiddersMore: true,
              biddersPage: page
            })
          }
        }
      })
  },

  /**
   * 竞拍记录查看更多
   */
  biddresSeeMoreClick: function () {
    let page = this.data.biddersPage + 1
    this.setData({
      userId: app.globalData.userId,
      biddersPage: page
    })
    this.showBiddersData()
  },

  /**
   * 请求故事详情页
   */
  showStoryDetails: function () {
    var that = this
    var param = {
      storyId: this.data.goodsId
    }
    mRequest.getStoryDetails(param,
      function (data) {
        console.log('请求故事详情页  成功')
        that.setSwiperData(data.urls)
        that.setData({
          storyDetailsData: data,
          swiperData: data.urls,
          userName: data.fromName,
          userUrl: data.fromUrl,
          isPraiseVisible: true
        })
        // 处理轮播图数据
        that.initSwiper(data.urls.length)
        // 查看是否关注过
        that.followView.showFans(data.id)
        // 物品介绍和价钱View
        that.goodsInfoView.initStoryData(data, intentType)
        // 设置播放按钮是否显示
        if (data.urls) {
          if (data.urls[0].video) {
            that.setData({
              isStartVisible: false
            })
          }
        }
        // 自己发布的商品
        if (app.globalData.userId == data.fromId) {
          that.setData({
            isTabRightVisible: true,   // 底部tab按钮消失
            isFollowVisible: true,     // 关注的人
          })
        }
      })
  },

  /**
   * 可能认识的人
   */
  showUserFollower: function () {
    var that = this
    mRequest.getUserFollower(
      function (data) {
        console.log('可能认识的人  成功')
        that.setData({
          userFollowerData: data
        })
      }
    )
  },

  /**
   * 更多商品加载更多
   */
  moreLoadListener: function () {
    this.moreList.reachBottom()
  },
  onReachBottom: function (e) {

  },
  /**
   * 更多List的Item点击事件
   */
  itemClick: function (e) {
    let id = e.detail.detail.id
    wx.switchTab({
      url: '/goods/pages/goodsDetails/goodsDetails?goods_type=' + intentType + '&goods_id=' + id,
    })
    // wx.navigateTo({
    //   url: '/goods/pages/goodsDetails/goodsDetails?goods_type=' + intentType + '&goods_id=' + id,
    // })
  },

  /**
   * 获取已领取该商品的人
   */
  showObtainSuccessPeople: function () {
    var that = this
    var param = {
      goodsId: this.data.goodsId
    }
    mRequest.getObtainSuccessPeople(param,
      function (data) {
        console.log('获取已领取该商品的人  成功')
        if (data) {
          if (data.length && data.length > 0) {
            that.data.isObtainVisible = false
          } else {
            that.data.isObtainVisible = true
          }
          that.setData({
            redObtainData: data,
            obtainNum: data.length,
            isObtainVisible: that.data.isObtainVisible
          })
        } else {
          that.setData({
            isObtainVisible: true
          })
        }
      }
    );
  },

  /**
   * 根据商品ID获取该商品详情
   */
  showGoodsDetails: function () {
    var that = this
    var param = {
      id: this.data.goodsId
    }
    mRequest.getGoodsDetails(param,
      function (data) {
        console.log('根据商品ID获取该商品详情  成功')
        that.setSwiperData(data.files.filePaths)
        that.setData({
          goodsDetailsData: data,
          swiperData: data.files.filePaths,
          rewardIntegral: data.rewardIntegral,
          userName: data.userName,
          userUrl: data.userAvatar
        })
        if (intentType == constant.BIDDERS) {
          // 获取竞拍记录接口
          that.showBiddersData()
          // 查询竞拍信息接口
          that.showBiddersInfo()
          // 只有上架才显示竞拍时间
          that.setData({
            isBiddersVisible: data.goodsListEntity.status == 2 ? false : true
          })
        }
        // 获取运费
        that.showFreight(data)
        // 刷新自己的果冻
        app.globalData.userSweets = data.userIntegral
        // 处理轮播图数据
        that.initSwiper(data.files.filePaths.length)
        // 更新赞赏的数据
        that.praiseView.initData(data, that.data.goodsId)
        // 物品介绍和价钱View
        that.goodsInfoView.initGoodsData(data, intentType)
        // 砍果冻传递数据
        that.cutJellyView.setGoodsDetailsData(data)
        // 处理轮播图播放按钮
        if (data.files.filePaths[0].video) {
          that.setData({
            isStartVisible: false
          })
        }
        // 查看是否关注过
        that.followView.showFans(data.goodsListEntity.publishUserId)
        // 用户状态 0、自己，1、其他人
        if (data.userStatus == 0) {
          that.setData({
            tabRghtText: '编辑',
            isFollowVisible: true,     // 关注的人
            isInvitationVisible: true  // 砍花记录
          })
        }

        // 库存商品<=0 已卖出
        // 已赠送
        if (data.goodsListEntity.count <= 0) {
          that.setData({
            tabRghtText: '已赠送',
            isBottomRight: true    // 右侧按钮变灰
          })
        }

        // 判断商品是否已下架
        if (data.goodsListEntity.status == -1) {
          that.setData({
            isStatusVisible: false,// 顶部状态显示
            titleDetailsStatus: '已下架',
            isBiddersVisible: true,// 竞拍时间隐藏
          })
          // 其他人的时候显示已下架不让点击
          if (data.userStatus == 1) {
            that.setData({
              tabRghtText: '已下架',
              isBottomRight: true    // 右侧按钮变灰
            })
          }
        }

        // 审核未通过 (只有自己可以看)
        if (data.goodsListEntity.status == 1) {
          that.setData({
            isBiddersVisible: true,// 竞拍时间隐藏
            isStatusVisible: false, // 顶部状态显示
            titleDetailsStatus: '审核未通过',
          })
        }
        // 审核中 (只有自己可以看)
        if (data.goodsListEntity.status == 0) {
          that.setData({
            isBiddersVisible: true,// 竞拍时间隐藏
            isStatusVisible: false, // 顶部状态显示
            titleDetailsStatus: '审核中',
          })
        }
      },
      function (error) {
        that.setData({
          isShareImgVisible: true
        })
      });
  },

  /**
   * 获取运费
   */
  showFreight: function (data) {
    let that = this
    //判断是否免邮费
    if (data.goodsListEntity.postage == -1) {
      that.setData({
        freightData: 0
      })
    } else {

      let prama = {
        sellUserId: data.goodsListEntity.publishUserId,
        buyUserId: app.globalData.userId,
        goodsId: this.data.goodsId
      }

      mRequest.getFreight(prama,
        function (success) {
          that.setData({
            freightData: success
          })
        })
    }

  },

  /**
   * 处理轮播图数据
   */
  setSwiperData: function (list) {
    for (var i = 0; i < list.length; i++) {
      if (list[i].video) {
        let imageUrl = ''
        let url = list[i].video
        let index = url.lastIndexOf('/')
        let startUrl = url.substring(0, index) + '/zoom/'

        let str = url.substring(index + 1, url.length);
        let strIndex = str.lastIndexOf('.')
        let endUrl = str.substring(0, strIndex) + '.jpg'

        list[i].img = startUrl + endUrl
      }
    }
  },

  handleIntentData: function (options) {
    console.log("***********收到的数据" + JSON.stringify(options))
    if (options.goods_type) {
      intentType = options.goods_type  // 页面跳转的类型
    }
    let friendId = ''
    if (options.friendId) {
      // 从微信分享页面点进来的
      friendId = options.friendId
    }
    // 设置帮忙砍花朋友的Id
    this.cutJellyView.initFirendId(friendId, options.goods_id)

    this.setData({
      goodsId: options.goods_id
    })

    if (intentType == constant.DEFAULT) {
      // 默认详情页
      this.setData({
        tabRghtText: '要了'
      })
    } else if (intentType == constant.BIDDERS) {
      // 竞拍详情页
      this.setData({
        tabRghtText: '立即竞拍',
        isBiddersVisible: false, //是不是竞拍中
        isInvitationVisible: true,  // 邀请好友砍花 和砍花记录
      })
    } else if (intentType == constant.STORY) {
      wx.setNavigationBarTitle({
        title: '故事详情'//页面标题为路由参数
      })
      // 故事详情页
      this.setData({
        isInvitationVisible: true,// 邀请好友砍花 和砍花记录
        isTabRightVisible: true,  // 底部按钮右边隐藏
        isObtainVisible: true,    // 领取成功
        tabRghtText: '赞赏一个果冻',
      })
    } else if (intentType == constant.RED_PACKAGE) {
      // 新人领红包详情页
      this.setData({
        isInvitationVisible: true,  // 邀请好友砍花 和砍花记录
        tabRghtText: '立即获得'
      })
    } else if (intentType == constant.ONE_MONEY) {
      this.setData({
        isTabLeftVisible: true,   // tab底部左边隐藏 --抢兑
        isInvitationVisible: true,// 邀请好友砍花 和砍花记录
        isObtainVisible: true,    // 领取成功
        isFollowRootVisible: true, // 关注view是否显示
        isPraiseVisible: true,     // 赞赏果冻
        tabRghtText: '0元抢兑'
      })
    }
  },

  initSwiper: function (length) {
    // 设置轮播图总的数量
    this.setData({
      swiperLength: length
    })
  },

  /**
   * 要了----> 确认出果冻点击事件
   */
  defultTabClick: function () {
    var that = this
      this.payPopuWindow.hide()
      var param = {
        userId: app.globalData.userId,
        goodsId: this.data.goodsId,
        integral: this.data.goodsDetailsData.goodsListEntity.integral,
        count: 1,
        postage: this.data.freightData,
        receiveNamestring: this.data.defaultAddressData.name,
        receivePhonestring: this.data.defaultAddressData.phone,
        receiveAddress: this.data.defaultAddressData.region + this.data.defaultAddressData.address,
        addressId: this.data.defaultAddressData.id
      }
      mRequest.payDefultGoods(param,
        function (data) {
          console.log('要了确认出果冻  成功')
          // 刷新物品详情接口
          that.showGoodsDetails()
          if (that.data.goodsDetailsData.goodsDetailType == 1){
            var param = {};
            param["saleTypeId"] = 5;
            param["goodsId"] = that.data.goodsId;
            // 跳支付成功页面
            wx.navigateTo({
              url: "/pages/common/paySuccess/paySuccess?result=1&type=1" + "&goodsData=" + JSON.stringify(param)
            })
          }else{
            wx.navigateTo({
              url: '/pages/orderDetails/OrderDetails?order_id=' + data.id
            })
          }
         
        })
  },

  /**
   * 修改收货地址（竞拍、要了、抢兑）
   */
  modifyAddressClick: function () {
    wx.navigateTo({
      url: '/pages/addProduct/myAddress/myAddres',
    })
  },

  /**
   * 立即竞拍--->确认出果冻点击事件
   */
  biddersTabClick: function () {
      this.biddersPopuWindow.hide()
      this.showCommitMonetData()
  },

  /**
   * 点立即竞拍确认出果冻 和快速出花
   */
  showCommitMonetData: function () {
    // 竞拍已结束不让再次竞拍
    if (intentType == constant.BIDDERS && this.data.biddresInfo.auctionStatus != 0) {
      wx.showToast({
        title: '竞拍已结束',
        icon: 'none',
        duration: 2000,
      })
      return
    }

    // 竞拍需要添加地址
      var that = this
      if (this.data.inputValue < this.data.goodsDetailsData.goodsListEntity.integral) {
        this.showTost('出价不能低于当前最后一次叫价')
        return
      }

      var param = {
        goodsId: this.data.goodsId,
        userId: app.globalData.userId,
        userRealinfoId: this.data.defaultAddressData.id,
        costIntegral: this.data.inputValue
      }

      mRequest.commitCandy(param,
        function (data) {
          that.showTost('竞拍成功')
          // 刷新物品详情接口
          that.showGoodsDetails()
          // 刷新竞拍记录接口
          that.setData({
            startPage: 0
          })
          that.showBiddersData()
        }
      )
  },

/**
 * 返回首页
 */
  backHome:function () {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },

  /**
   * 提交formid
   */
  submitForm: function (e) {
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId, 14);
  },
  /**
 * 竞拍快速出花 +5 颗果冻 
 */
  addMoneyClick: function () {
    // 竞拍把input值改为商品值 + 5
    this.setData({
      inputValue: this.data.goodsDetailsData.goodsListEntity.integral + 5
    })
    this.biddersPopuWindow.show();
    // this.setData({
    //   isSpeedVisible: false
    // })
  },

  /**
   * 快速出花取消回调
   */
  cancelCallBack: function () {
    this.setData({
      isSpeedVisible: true
    })
  },

  /**
   * 点击领取成功人物头像
   */
  clickObationItem: function (data) {
    wx.navigateTo({
      url: '/mineSubs/pages/homepage/personalhomepage?userId=' + data.currentTarget.dataset.itemdata.userId
    })
  },

  /**
   * 快速出花确定回调
   */
  confirmCallBack: function () {
    // 竞拍把input值改为商品值 + 5
    this.setData({
      inputValue: this.data.goodsDetailsData.goodsListEntity.integral + 5,
      isSpeedVisible: true
    })
    this.showCommitMonetData()
  },

  /**
   * 输入的果冻数量
   */
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  /**
   *  点击关注的人
   */
  clickReleasePeople: function () {
    wx.navigateTo({
      url: '/mineSubs/pages/homepage/personalhomepage?userId=' + this.data.goodsDetailsData.goodsListEntity.publishUserId
    })
  },

  /**
   * 轮播图滑动的监听事件
   */
  swiperEvent: function (e) {
    let swiperCurrent = e.detail.current + 1
    let isStartVisible = true
    if (this.data.swiperData[e.detail.current].video) {
      isStartVisible = false
    } else {
      isStartVisible = true
    }
    // 设置播放按钮是否显示/ 当前播放的坐标
    this.setData({
      swiperCurrent: swiperCurrent,
      isStartVisible: isStartVisible
    })
  },

  /**
   * 视频播放点击事件
   */
  swiperVideoClick: function (e) {
    let current = this.data.swiperCurrent - 1;
    let item = this.data.swiperData[current]
    // 视频播放
    if (item.video) {
      this.setData({
        storyVideourl: item.video,
        isStartVisible: true,
        autoplay: false
      })
      this.showVideo.show()
    } else {
      let urls = []
      for (let i = 0; i < this.data.swiperData.length; i++) {
        let img = this.data.swiperData[i].img
        if (this.data.swiperData[i].video == "") {
          let str = img.replace("zoom/","")
          urls.push(str)
        }else{
          urls.push(img)
        }
      }
      // 图片预览
      wx.previewImage({
        current: item.img.replace("zoom/", ""),
        urls: urls
      })
    }
  },

  /**
   * 视频取消回调
   */
  videoViewDimiss: function () {
    this.setData({
      isStartVisible: false,
    })
  },

  initTime: function () {
    var that = this
    setTimeout(function () {

      that.initTime()
    }, 2000) //延迟时间 这里是1秒  
  },

  /**
   *  跳转消息
   */
  serveAction: function (e) {
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId, 6);
    console.log("formId-6", formId)
    wx.switchTab({
      url: '/pages/mine/message/message',
    })
  },
  /**
   * scroll滚动时触发
   */
  scroll: function (e) {
    var that = this
    let x = e.detail.deltaX;
    let y = e.detail.deltaY;
    let top = e.detail.scrollTop;
    let height = e.detail.scrollHeight;
    // console.log("scroll x:" + x);
    // console.log("scroll y:" + y);
    // console.log("scroll scrollTop:" + top);
    // console.log("scroll scrollHeight:" + height);
    // console.log("listPosition:" + listPosition);

    if (top - listPosition >= 0) {
      this.actionView.showBack(function () {
        that.gotoTop()
      })
    } else {
      this.actionView.dismissBack()
    }
  },

  /**
  * 计算view的坐标
  */
  queryMultipleNodes: function () {
    var query = wx.createSelectorQuery()
    query.select('#more-list').boundingClientRect()
    query.exec(function (res) {
      listPosition = res[0].top;
      // console.log("view top: " + res[0].top);
    })
  },

  gotoTop: function () {
    this.setData({
      scrollTop: 0
    })
  },

  showTost: function (str) {
    wx.showToast({
      title: str,
      icon: 'none',
      duration: 1000,
      mask: true
    })
  },

  /**
   * 底部右键按钮点击事件
   */
  tabBottomRight: function () {
    // 其他人、下架处理
    if (this.data.goodsDetailsData.goodsListEntity.status == -1 && this.data.goodsDetailsData.userStatus == 1) {
      // if (this.data.goodsDetailsData.goodsListEntity.status == -1) {
      this.showTost('此商品已下架')
      return
    }
    // 编辑
    if (this.data.goodsDetailsData.userStatus == 0) {
      if (this.data.isBiddersVisible == false) {
        if (this.data.biddresInfo.auctionStatus == undefined || this.data.biddresInfo.auctionStatus == null) {
          // 编辑
          wx.navigateTo({
            url: '/pages/addProduct/compileProduct/compipleProduct?id=' + this.data.goodsId
          })
          return
        }
        if (this.data.biddresInfo.auctionStatus != 1) {
          // 编辑
          wx.navigateTo({
            url: '/pages/addProduct/compileProduct/compipleProduct?id=' + this.data.goodsId
          })
        } else {
          this.showTost('竞拍已结束')
        }
      } else {
        if (this.data.goodsDetailsData.goodsListEntity.count <= 0) {
          this.showTost('商品已赠送')
          return
        }
        // 编辑
        wx.navigateTo({
          url: '/pages/addProduct/compileProduct/compipleProduct?id=' + this.data.goodsId
        })
      }
      return
    }
    if (intentType == constant.DEFAULT) {
      // 已卖出
      if (this.data.goodsDetailsData.goodsListEntity.count <= 0) {
        wx.showToast({
          title: '商品已赠送',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      // 要了
      if (this.data.defaultAddressData && this.data.defaultAddressData.address) {
        this.payPopuWindow.show();
      } else {
        wx.navigateTo({
          url: '/pages/addProduct/myAddress/myAddres',
        })
      }
    } else if (intentType == constant.BIDDERS) {
      // 立即竞拍
      if (this.data.biddresInfo.auctionStatus == 1) { // 0进行中，1结束
        // 竞拍已结束
        return
      }
      // 竞拍把input值改为商品值 + 5
      if (this.data.defaultAddressData && this.data.defaultAddressData.address) {
        this.setData({
          inputValue: this.data.goodsDetailsData.goodsListEntity.integral + 5
        })
        this.biddersPopuWindow.show();
      } else {
        wx.navigateTo({
          url: '/pages/addProduct/myAddress/myAddres',
        })
      }
    } else if (intentType == constant.STORY) {
      // 赞赏一个果冻
    } else if (intentType == constant.ONE_MONEY) {
      // 立即抢兑
      if (this.data.defaultAddressData && this.data.defaultAddressData.address) {
        if (this.data.goodsDetailsData.goodsListEntity.count <= 0) {
          this.showTost('商品已赠送')
          return
        }
        this.robbingPopWindow.show()
      } else {
        wx.navigateTo({
          url: '/pages/addProduct/myAddress/myAddres',
        })
      }
    }
  },

  /**
   * 点击0元抢兑
   */
  robbingClick: function () {
    var that = this
    let parmas = {
      userId: app.globalData.userId,
      goodsId: this.data.goodsId,
      integral: this.data.goodsDetailsData.goodsListEntity.integral,
      count: 1,
      postage: this.data.freightData,
      receiveNamestring: this.data.defaultAddressData.name,
      receivePhonestring: this.data.defaultAddressData.phone,
      receiveAddress: this.data.defaultAddressData.region + this.data.defaultAddressData.address,
      addressId: this.data.defaultAddressData.id
    }
    mRequest.putRobBuy(parmas,
      function (data) {
        // 刷新果冻数量
        that.showGoodsDetails()
        that.showTost('抢兑成功')
        if (that.data.goodsDetailsData.goodsDetailType == 1) {
          var param = {};
          param["saleTypeId"] = 5;
          param["goodsId"] = that.data.goodsId;
          // 跳支付成功页面
          wx.navigateTo({
            url: "/pages/common/paySuccess/paySuccess?result=1&type=1" + "&goodsData=" + JSON.stringify(param)
          })
        } else {
          wx.navigateTo({
            url: '/pages/orderDetails/OrderDetails?order_id=' + data.id
          })
        }
      })
  },

  //点击了他们的商品
  possibleFriendsCheck: function () {
    console.log("点击了他们的商品")
    wx.navigateTo({
      url: '/pages/home/products/products?type=-5',
    })
  },

  onShareAppMessage: function (res) {
    var title = ''
    var path = ''
    if (res.from === 'button') {
      
      if (res.target.dataset.id == 6) {
        // 邀请好友砍价
        title = this.data.cantangShareMsg
        title = title.replace(/#/, app.globalData.userInfo.nickName)
        title = title.replace(/{}/, this.data.goodsDetailsData.goodsListEntity.name)

        title = title
        var param = '?friendId=' + app.globalData.userId + '&goods_id=' + this.data.goodsId + '&goods_type=' + intentType + '&userId=' + app.globalData.userId
        path = 'goods/pages/goodsDetails/goodsDetails' + param
      } else{
        if (this.data.goodsDetailsData.isbuy == true){
          title = this.data.isBuyShareMsg
        }else{
          title = this.data.shareMsg
        }
        title = title.replace(/#/, app.globalData.userInfo.nickName)
        if (intentType == constant.STORY) {
          title = this.data.storyDetailsData.storyTitle
        } else {
          title = title.replace(/{}/, this.data.goodsDetailsData.goodsListEntity.name)
        }
        // 一键分享
        title = title
        path = 'goods/pages/goodsDetails/goodsDetails?goods_id=' + this.data.goodsId + '&goods_type=' + intentType + '&userId=' + app.globalData.userId
      }
    } else {
      // 顶部分享
      if (this.data.goodsDetailsData.isbuy == true) {
        title = this.data.isBuyShareMsg
      } else {
        title = this.data.shareMsg
      }
      title = title.replace(/#/, app.globalData.userInfo.nickName)
      if (intentType == constant.STORY) {
        title = this.data.storyDetailsData.storyTitle
      } else {
        title = title.replace(/{}/, this.data.goodsDetailsData.goodsListEntity.name)
      }

      title = title
      path = 'goods/pages/goodsDetails/goodsDetails?goods_id=' + this.data.goodsId + '&goods_type=' + intentType + '&userId=' + app.globalData.userId
    }

    let that = this
    return {
      title: title,
      path: path,
      imageUrl: intentType == constant.STORY ? this.data.storyDetailsData.urls[0].img : this.data.goodsDetailsData.goodsListEntity.cover,
      success: function (res) {
        let param = {
          userId: app.globalData.userId,
          goodsId: that.data.goodsId,
          description: '商品分享'
        }
        mRequest.saveShare(param,
          function () {
            console.log('分享成功，数据保存成功')
          })
      },
      fail: function (res) {
      }
    }
  },
})